package cn.com.greatwall.flowable.service.mapstruct;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.IdentityService;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.springframework.stereotype.Component;

import cn.com.greatwall.common.base.BaseMapper;
import cn.com.greatwall.flowable.service.dto.IdentityLinkDto;
import lombok.RequiredArgsConstructor;

/**
 * @Author herw
 * @Time 2020-11-19 16:49:58
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
@Component
@RequiredArgsConstructor
public class IdentityLinkMapper implements BaseMapper<IdentityLinkDto, IdentityLink> {
    private final IdentityService identityService;

    @Override
    public IdentityLink toEntity(IdentityLinkDto dto) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public IdentityLinkDto toDto(IdentityLink entity) {
        IdentityLinkDto dto = new IdentityLinkDto();
        if (entity.getGroupId() != null) {
            dto.setIdentityType("2");
            dto.setIdentityId(entity.getGroupId());
            dto.setIdentityName(getGroupName(entity.getGroupId()));
        } else if (entity.getUserId() != null) {
            dto.setIdentityType("1");
            dto.setIdentityId(entity.getUserId());
            dto.setIdentityName(getUserName(entity.getUserId()));
        }
        
        return dto;
    }

    @Override
    public List<IdentityLink> toEntity(List<IdentityLinkDto> dtoList) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<IdentityLinkDto> toDto(List<IdentityLink> entityList) {
        List<IdentityLinkDto> dtoList = new ArrayList<>();
        for (IdentityLink instance : entityList) {
            dtoList.add(toDto(instance));
        }
        return dtoList;
    }

    /**
     * 获取岗位名称
     * @param groupId /
     * @return
     */
    private String getGroupName(String groupId) {
        if (StringUtils.isEmpty(groupId)) {
            return null;
        }
        Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
        if (group != null) {
            return group.getName();
        }
        return null;
    }
    
    /**
     * 获取用户名称
     * @param userId /
     * @return
     */
    private String getUserName(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null) {
            return user.getFirstName();
        }
        return null;
    }
}
